<?php

class LabsController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/labs';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			array('COutputCache + view,sview', 'cacheID'=>'lab_view','duration'=>120, 'varyByParam'=>array('id'))
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view','sview','css','html5','php','demo','listpage','list','tags'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update','solution','usolution','dsolution','cdemo'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		
		$model = $this->loadModel($id);
        
        UtilStatistics::hitAdd($model, 'pro_hits');
        
		
		$solutionModel=new Solution;
		
		$solution = new CActiveDataProvider('Solution',array(
			'criteria'=>array(
				'condition'=>'sol_pid = :pid',
				'order'=>'sol_id DESC',
				'params'=>array(
					':pid'=>$model->pro_id
				)
			)
		));
		
		$this->render('view',array(
			'model'=>$model,
			'solution'=>$solution,
			'solutionModel'=>$solutionModel
		));
	}
	
	public function actionCss()
	{
		$this->layout = '//layouts/preview';
		
		$this->render('css');
	}
	
	public function actionHtml5()
	{
        $this->layout = '//layouts/preview';
		$this->render('html5');
	}
    
    public function actionCdemo()
    {
        $this->layout = '//layouts/preview';
        
        if(isset($_POST['Artical'])){

		$model=new Article;

		// Uncomment the following line if AJAX validation is needed
		$this->performAjaxValidation($model);
	
			$model->attributes = $_POST['Article'];
			$model->arc_ctype = Category::CONTENT_STORY;
			$model->arc_cid = $_POST['Article']['arc_cids'];
			$model->arc_created = time();
			
			UtilTools::writeToFile($_POST);
			
//			UtilTools::dump($_REQUEST);
//			Yii::app()->end();
			
			Tag::model()->insertTags($model->arc_tags, Category::CONTENT_STORY);
			
			//Note:此处传递数据$_POST['Article']['arc_result']
			if ($similarfile = $this->getSimilarFile($_POST['Article']['arc_content'])){
				unlink($similarfile);
			}
			
			if($model->save())
			{
				$this->redirect(array('view','id'=>$model->arc_id));
				
			}
			else 
			{
				UtilTools::writeToFile(CHtml::errorSummary($model));
			}
			
			Yii::app()->end();

        }
        
        $this->render('cdemo');
    }
	
	public function actionDemo()
	{
        $this->layout = '//layouts/preview';
		$this->render('demo');
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new Project;
		
		// Uncomment the following line if AJAX validation is needed
		$this->performAjaxValidation($model);
		
		UtilHelper::writeToFile($_SESSION);		
		
		session_start();
		
		if(isset($_SESSION['project_created_id']))
		{
			unset($_SESSION['project_created_id']);
		}
		


		if(isset($_POST['Project']))
		{
			$model->attributes=$_POST['Project'];   
            $model->pro_cid = $_POST['Project']['cids'];
			
			if( $model->save())
			{
				//echo "success_#_".$this->createUrl('solution', array('id'=>$model->pro_id));
                
//                 Yii::app()->user->setFlash('successInfo', '文章发表成功，'.CHtml::link('继续发表', array('/labs/create')).CHtml::link('查看发表文章',array('/labs/view',array('id'=>$model->pro_id))));
				$str = 'Congratulation!  have published you article, <span style="color:red">'.CHtml::link('write more',array('/labs/create')).' </span>, or<span style="color:red">'.CHtml::link('view the article', array('/labs/view','id'=>$model->pro_id)).'</span>';
// 				$str = 'Congratulations, article publishing success, write another one, or view the published article';

				//特别说明：因为在使用中文时不能正常使用Yii::app()->user->getFlash("success",$str);所以再次使用SESSION传值
				
				session_start();
				
				$_SESSION['project_created_id'] = $model->pro_id;
				
				
				Yii::app()->user->setFlash('success', $str);
				
				UtilHelper::writeToFile($_SESSION,'a+');
				
                $this->refresh();
                
			}else{
				
				UtilHelper::dump(CHtml::errorSummary($model));
				
				die();
				
			}

		}

		$this->render('create',array(
			'model'=>$model,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		$this->performAjaxValidation($model);

		if(isset($_POST['Project']))
		{
			$model->attributes=$_POST['Project'];
			
			UtilTools::writeToFile($model->attributes);
			
			if($model->save())
			{
//				echo "success_#_".$this->createUrl('view', array('id'=>$model->pro_id));
				$this->redirect(array('view','id'=>$model->pro_id));
			}
			else
			{
				UtilTools::writeToFile(CHtml::errorSummary($model));	
				
			} 
			Yii::app()->end();
			
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		if(Yii::app()->request->isPostRequest)
		{
			// we only allow deletion via POST request
			$this->loadModel($id)->delete();

			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if(!isset($_GET['ajax']))
				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}
	
	
	public function actionSolution($id)
	{
		$project = Project::model()->findByPk($id);
		
	    if($project===null)
			throw new CHttpException(404,'The requested page does not exist.');		
			
		$model=new Solution;
	
	    // uncomment the following code to enable ajax-based validation
	    
	    if(isset($_POST['ajax']) && $_POST['ajax']==='solution-form')
	    {
	        echo CActiveForm::validate($model);
	        Yii::app()->end();
	    }
	    
	
	    if(isset($_POST['Solution']))
	    {
	        $model->attributes=$_POST['Solution'];
	        
	        UtilTools::writeToFile($model->attributes);
	        if($model->validate())
	        {
	            // form inputs are valid, do something here
	           	if($model->save())
				{
					//echo "success_#_".$this->createUrl('sview', array('id'=>$model->sol_id));

					$str = 'Congratulation!  have published you article, <span style="color:red">'.CHtml::link('write more',array('/labs/create')).' </span>, or<span style="color:red">'.CHtml::link('view the article', array('/labs/sview','id'=>$model->sol_id)).'</span>';

				
				
					Yii::app()->user->setFlash('success', $str);

                    $this->refresh();
				}
	
	            return;
	        }
	    	else 
			{
				UtilTools::writeToFile(CHtml::errorSummary($model));
			}
	    }

	    
	    $this->render('solution',array(
	    		'model'=>$model,
	    		'project'=>$project
	    ));
	}
	
	public function loadSolutionModel($id)
	{
		$model=Solution::model()->findByPk($id);
	    
	    if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
			
		return $model;
		
	}
	
	public function actionUsolution($id)
	{

		$model = $this->loadSolutionModel($id);
	
	    if(isset($_POST['Solution']))
	    {
	        $model->attributes=$_POST['Solution'];
	        
	        UtilHelper::writeToFile($model->attributes);
	        if($model->validate())
	        {
	            // form inputs are valid, do something here
	           	if($model->save())
				{
					echo "success_#_".$this->createUrl('sview', array('id'=>$model->sol_id));

                    
                    $this->redirect(array('sview', 'id'=>$model->sol_id));
				}
	
	            return;
	        }
	    	else 
			{
				UtilHelper::writeToFile(CHtml::errorSummary($model));
			}
	    }
	    $this->render('usolution',array('model'=>$model));
	}
	
	public function actionSview($id)
	{
		$model = $this->loadSolutionModel($id);
        
        //点击量统计
        UtilStatistics::hitAdd($model, 'sol_hits');
		
		$this->render('sview',array(
			'model'=>$model
		));
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$criteria = new CDbCriteria(array(
			'order'=>'pro_id DESC'
		));		
		
// 		$total = Project::model()->count();
		
// 		$pages = new CPagination($total);
// 		$pages->pageSize = 10;
// 		$pages->applyLimit($criteria);
		
// 		$dataProvider = Project::model()->findAll($criteria);
		
// 		$this->render('index',array(
// 			'dataProvider'=>$dataProvider,
// 			'pages'=>$pages
// 		));


		$dataProvider=new CActiveDataProvider('Project',array(
				'criteria'=>$criteria,
				'pagination'=>array(
						'pageSize'=>10
				)
		));
		
		
		$this->render('index',array(
				'dataProvider'=>$dataProvider,
		));
	}
	
    public function actionTags()
    {
    	$tag = urldecode($_GET['tag']);
    	
    	if(!isset($tag))
    		throw new CHttpException(404,'请求页面不存在~~.');
    	
    	$this->meta['Description'] = '本站关于标签为“'.$tag.'”的博文';
    	$this->meta['KeyWords'] = $tag;
    	
    	$this->setMetaInfo();
    	
    	$criteria = new CDbCriteria();

    	$criteria->addSearchCondition('pro_tags',$tag);
    	
    	
    	
    	$dataProvider=new CActiveDataProvider('Project',array(
    			'criteria'=>$criteria,
    			'pagination'=>array(
    					'pageSize'=>10
    			)
    	));
    		
    	$this->render('tags',array(
    			'dataProvider'=>$dataProvider
    	));
    	
	}
	
	public function actionList($id)
	{
		$criteria = new CDbCriteria(array(
				'condition'=>'pro_cid = :cid',
				'order'=>'pro_id DESC',
				'params'=>array(
							':cid'=>$id
						)
		));		
		
		$dataProvider=new CActiveDataProvider('Project',array(
				'criteria'=>$criteria,
				'pagination'=>array(
						'pageSize'=>10
				)
		));
		
		
		$this->render('list',array(
				'dataProvider'=>$dataProvider,
		));		
	}
	
	
	public function actionListPage()
	{
		$id = $_GET['id'];
		$num = $_GET["num"]?$_GET['num']:10;
		$page = $_GET["page"]?$_GET['page']:1;
		
		//		UtilHelper::dump($_GET);
		
		$data = array();
		$i=0;
		$pageSize = 10;
		
		$criteria = new CDbCriteria(array(
				'order'=>'pro_id DESC',
				'limit'=>$page*$pageSize.','.$pageSize,
				'params'=>array(
				)
		));
		
		$count= Project::model()->count($criteria);
		$pages=new CPagination($count);
		
		// results per page
		$pages->pageSize=$pageSize;
		$pages->applyLimit($criteria);
		$model = Project::model()->findAll($criteria);
		
		
		if($page < $pages->getPageCount()){
				
			foreach ($model as $item)
			{
		
				$data[$i]['img'] = '';//UtilHelper::strSlice(strip_tags($item->pro_introduce),0,220) ;//File::model()->generateFilePath($item, false,false);
				$data[$i]["height"] = 0; //无高度值
				$data[$i]["title"] = UtilHelper::strSlice(strip_tags($item->pro_introduce),0,220) ."<hr class='clearfix' />ID：".$item->pro_id."<br />时间：".date("Y-m-d H:i:s",$item->pro_created)."<br />".($i+1)."、WindsWaterFlow(第".$page."页)";
				$data[$i]['dkdk'] = $_GET;
				$i++;
			}
				
		}
		
		UtilHelper::writeToFile($data);
		
		echo json_encode($data);		
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Project('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Project']))
			$model->attributes=$_GET['Project'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=Project::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='project-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
